package routers

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"os"
	"path/filepath"
)

type FileParam struct {
	FileName string `json:"fileName"  form:"fileName" required:"true"`
}

func Download(engine *gin.Engine) {

	engine.Static("/static", "./static")
	engine.GET("/getCurFileList", func(ctx *gin.Context) {
		var files []string

		root := "./upload"
		err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
			if !info.IsDir() {
				files = append(files, path)
			}
			return nil
		})
		if err != nil {
			return
		}
		ctx.JSON(http.StatusOK, gin.H{"files": files})
	})
	engine.GET("/download", func(ctx *gin.Context) {
		ctx.HTML(http.StatusOK, "download.html", gin.H{})
	})
	engine.POST("/download", func(ctx *gin.Context) {
		var param FileParam
		if err := ctx.ShouldBind(&param); err != nil {
			ctx.String(http.StatusBadGateway, err.Error())
			return
		}
		ctx.Header("Content-Type", "application/octet-stream")
		ctx.Header("Content-Disposition", "attachment; filename="+param.FileName)
		ctx.File("upload/" + param.FileName)
	})
}
